﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Entities = GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class Dealers : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
        }

        #endregion

        #region Button Events


        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            var frc = new Components.DealerComponent();
            try
            {
                var Dealer = ReadDealer();
                if (hfDealerID.Value.Trim() != string.Empty)
                {
                    Dealer.DealerID = int.Parse(hfDealerID.Value);
                    var oldDealer = frc.GetDetails(Dealer.DealerID);
                    frc.Edit(Dealer);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.Dealer>
                    {
                        EntityKey = Dealer.DealerID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldDealer,
                        NewObject = Dealer,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Dealer>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Dealer was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save Dealer", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Dealer couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
           if (grvDealers != null)
            {
                if (grvDealers.SelectedDataKey != null)
                {
                    try
                    {
                        var DealerId = (int)this.grvDealers.SelectedDataKey.Value;
                        var frc = new Components.DealerComponent();
                        var Dealer = frc.GetDetails(DealerId);
                        txtDealerNumber.Text = Dealer.DealerNumber;
                        txtDealerName.Text = Dealer.DealerName;
                        txtRIF.Text = Dealer.DealerTaxID;
                        txtPhone.Text = Dealer.DealerPhoneNumber;
                        txtFax.Text = Dealer.DealerFaxNumber;
                        txtEmail.Text = Dealer.DealerElectronicMailAddress;
                        optOptions.SelectedValue = Dealer.Status.ToString();
                        txtAddress.Text = Dealer.DealerAddressLine1 + " " + Dealer.DealerAddressLine2 + " " + Dealer.DealerAddressLine3;
                        hfDealerID.Value = DealerId.ToString();
                        if (Dealer.DealerType != null)
                            ddlType.SelectedValue = ((int)Dealer.DealerType).ToString();

                        if (Dealer.DealerFI == true)
                            chkFI.Checked = true;
                        else
                            chkFI.Checked = false;
                        if (Dealer.DealerGlink == true)
                            chkGlink.Checked = true;
                        else
                            chkGlink.Checked = false;

                        if (Dealer.AccountRepresentativeID != null)
                            ddlAccountRepresentative.SelectedValue = Dealer.AccountRepresentativeID.ID.ToString();

                        if (Dealer.DealerState!= null)
                            ddlState.SelectedValue = Dealer.DealerState.ID.ToString();

                        if (Dealer.DealerGroupID != null)
                            ddlDealerGroup.SelectedValue = Dealer.DealerGroupID.ID.ToString();

                        btnSave.Visible = true;
                        //btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Dealer", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the Dealer.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Dealer must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
            
        }

        #endregion

        #region Other Events

        protected void grvDealers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvDealers, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[3].Text = "Active";
                }
                else
                {
                    e.Row.Cells[3].Text = "Inactive";
                }
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtDealerNumber.Text = string.Empty;
            txtDealerName.Text = string.Empty;
            txtRIF.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtFax.Text = string.Empty;
            txtEmail.Text = string.Empty;
            optOptions.SelectedValue = string.Empty;
            txtAddress.Text = string.Empty;
            hfDealerID.Value = string.Empty;
            ddlType.SelectedValue = string.Empty;
            chkFI.Checked = false;
            chkGlink.Checked = false;
            ddlAccountRepresentative.SelectedValue = string.Empty;
            ddlDealerGroup.SelectedValue = string.Empty;
            ddlState.SelectedValue = string.Empty;
        }
        private void Initialize()
        {
            try
            {
                //OJO Todo esto se llena de base de datos
                
                foreach (int i in Enum.GetValues(typeof(Entities.GeneralEnumTypes.TypeDealer)))
                {
                    this.ddlType.Items.Add(new ListItem(Enum.GetName(typeof(Entities.GeneralEnumTypes.TypeDealer), i).ToString().Replace('_', ' '), i.ToString()));
                }
                this.ddlType.Items.Insert(0, new ListItem("Select...", String.Empty));

                var bcDealerGroup = new Components.DealerGroupComponent();
                ddlDealerGroup.DataSource = bcDealerGroup.GetList();
                ddlDealerGroup.DataTextField = "Name";
                ddlDealerGroup.DataValueField = "ID";
                ddlDealerGroup.DataBind();
                ddlDealerGroup.Items.Insert(0, new ListItem("Select...", string.Empty));

                var bcAccountRepresentative = new Components.AccountRepresentativeComponent();
                ddlAccountRepresentative.DataSource = bcAccountRepresentative.GetList();
                ddlAccountRepresentative.DataTextField = "Name";
                ddlAccountRepresentative.DataValueField = "ID";
                ddlAccountRepresentative.DataBind();
                ddlAccountRepresentative.Items.Insert(0, new ListItem("Select...", string.Empty));

                var bcStates = new Components.StateComponent();
                ddlState.DataSource = bcStates.GetList();
                ddlState.DataTextField = "Name";
                ddlState.DataValueField = "ID";
                ddlState.DataBind();
                ddlState.Items.Insert(0, new ListItem("Select...", string.Empty)); 

                optOptions.SelectedValue = "True";
                btnSave.Visible = false;
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        private void ValidateSecurity()
        {
             var beEntities = ((Entities.User)Session["User"]).Role.Security.GetEntitySecurity("Dealers");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvDealers.Visible = false;
                btnModify.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
        }
        private int Search()
        {
           try
            {
                var bc = new  Components.DealerComponent();
                string DealerName = txtDealerNameSearch.Text;
                string DealerNumber = txtDealerNumberSearch.Text;
                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;

               

                Entities.DealerCollection Dealercollection = bc.Search(DealerName,DealerNumber, paging);

                grvDealers.DataSource = Dealercollection;
                grvDealers.DataBind();
                return Dealercollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Dealer", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return  0;

            }
        }
        private Entities.Dealer ReadDealer()
        {
            var Dealer = new  Entities.Dealer
            {
                
                DealerType = (Entities.GeneralEnumTypes.TypeDealer)Enum.Parse(typeof(Entities.GeneralEnumTypes.TypeDealer), ddlType.SelectedValue.ToString()),
                Status = bool.Parse(optOptions.SelectedValue),
             
           };
            if (!string.IsNullOrEmpty(ddlState.SelectedValue))
            {
                var bc= new GMAC.ReportingSystem.Business.Components.StateComponent();
                Dealer.DealerState = bc.GetDetails(ddlState.SelectedValue);
            }
            if (ddlAccountRepresentative.SelectedValue!=string.Empty)
            {
                Dealer.AccountRepresentativeID = new GMAC.ReportingSystem.Business.Entities.AccountRepresentative();
                Dealer.AccountRepresentativeID.ID = int.Parse(ddlAccountRepresentative.SelectedValue);
            }
            else
            {
                Dealer.AccountRepresentativeID = null;
            }
            if (ddlDealerGroup.SelectedValue!= string.Empty)
            {
                Dealer.DealerGroupID = new GMAC.ReportingSystem.Business.Entities.DealerGroup();
                Dealer.DealerGroupID.ID = int.Parse(ddlDealerGroup.SelectedValue);
            }
            else
            {
                Dealer.DealerGroupID =  new GMAC.ReportingSystem.Business.Entities.DealerGroup();
            }
            
            if (!string.IsNullOrEmpty(hfDealerID.Value))
            {
                Dealer.DealerID = int.Parse(hfDealerID.Value);
            }
            if (chkFI.Checked)
                Dealer.DealerFI = true; 
            else
                Dealer.DealerFI = false;

            if (chkGlink.Checked)
                Dealer.DealerGlink = true;
            else
                Dealer.DealerGlink = false; 
               
            return Dealer;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        #endregion

    }
}
